package com.undsf.atsuyuki;

import com.undsf.atsuyuki.entities.Article;
import com.undsf.atsuyuki.entities.Category;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Client {
    private String baseUrl;
    private String articleListSelector;
    private String articleTableSelector;
    private String titleNodeSelector;
    private String timeNodeSelector;
    private String authorNodeSelector;
    private String contentNodeSelector;
    private OkHttpClient httpClient;

    public Client() {
        httpClient = new OkHttpClient();
        baseUrl = "http://youth.tyust.edu.cn";
        articleListSelector = ".winstyle16900";
        articleTableSelector = ".winstyle16212";
        titleNodeSelector = ".titlestyle16212";
        timeNodeSelector = ".timestyle16212";
        authorNodeSelector = ".authorstyle16212";
        contentNodeSelector = "#vsb_content_2";
    }

    public List<Category> getCategories() {
        return null;
    }

    /**
     * 获取指定分类的所有文章
     * @param category
     * @return
     */
    public List<Article> getArticles(Category category) {
        return null;
    }

    public List<Article> getArticleIdList(int treeId) {
        return getArticleIdList(treeId, 1, 15);
    }

    /**
     * 获取指定节点下的所有文章（包含子节点）
     * @param treeId 节点ID
     * @param page 页码
     * @param count 数量
     * @return
     */
    public List<Article> getArticleIdList(int treeId, int page, int count) {
        String url = baseUrl + "/hd_list.jsp";
        Map<String, String> params = new HashMap<>();

        // ?a8t=94&a8p=1&a8c=1000&urltype=tree.TreeTempUrl&wbtreeid=1019
        // params.put("a8t", "");  // total 总页数
        params.put("a8p", page + "");
        params.put("a8c", count + "");
        params.put("urltype", "tree.TreeTempUrl");
        params.put("wbtreeid", treeId + "");

        String html = sendGetRequest(url, params);
        Document doc = Jsoup.parse(html);
        Element table = doc.select(articleListSelector).first();
        Elements lines = table.select("tr[height=20]");

        List<Article> articles = new ArrayList<>();
        for (Element line : lines) {
            Element titleNode = line.select(".c16900").first();
            Element timeNode = line.select(".timestyle16900").first();
            String title = titleNode.text();
            String time = timeNode.text().substring(0, 10);
            Article article = new Article(title, time, null, null);
            articles.add(article);
        }

        return articles;
    }

    public Article getArticle(int categoryId, int articleId) {
        String url = baseUrl + "/info/" + categoryId + "/" + articleId + ".htm";
        return getArticle(url);
    }

    public Article getArticle(String url) {
        String html = sendGetRequest(url);
        Document doc = Jsoup.parse(html);
        Elements results = doc.select(articleTableSelector);
        if (results.size() != 1) {
            // TODO 处理找不到文章的情况
            return null;
        }

        Element tableNode = results.get(0);
        Element titleNode = tableNode.select(titleNodeSelector).first();
        Element timeNode = tableNode.select(timeNodeSelector).first();
        Element authorNode = tableNode.select(authorNodeSelector).first();
        Element contentNode = tableNode.select(contentNodeSelector).first();

        // TODO 处理找不到节点的问题

        String title = titleNode.text();
        String publishTime = timeNode.text().substring(0, 10);
        String author = authorNode.text();
        String content = contentNode.text();
        Article article = new Article(title, publishTime, author, content);
        return article;
    }

    public String sendGetRequest(String url) {
        String content = null;
        try {
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Response response = httpClient.newCall(request).execute();
            // TODO 判断返回报文状态码
            content = response.body().string();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
        return content;
    }

    public String sendGetRequest(String url, Map<String, String> params) {
        StringBuffer strBuffer = new StringBuffer();
        strBuffer.append(url);
        boolean firstParam = false;
        if (url.contains("?") == false) {
            strBuffer.append("?");
            firstParam = true;
        }
        for(Map.Entry<String, String> entry : params.entrySet()) {
            if (firstParam) {
                firstParam = false;
            }
            else {
                strBuffer.append("&");
            }
            String param = entry.getKey() + "=" + entry.getValue();
            // TODO 需要URLencoding
            strBuffer.append(param);
        }
        return sendGetRequest(strBuffer.toString());
    }
}
